package xgin

import (
	"encoding/json"

	"gitee.com/xiaoyutab/xgotool/xstring"
	"github.com/gin-gonic/gin"
)

type midPage struct {
	Page  json.Number `json:"page" form:"page"`
	Limit json.Number `json:"limit" form:"limit"`
}
type midPages struct {
	Page  json.Number `json:"p0" form:"p0"`
	Limit json.Number `json:"p1" form:"p1"`
}

// 分页中间件
//
//	c	gin.Context对象
func Page(c *gin.Context) {
	if c.GetInt("limit") <= 0 {
		p1s := midPage{}
		p2s := midPages{}
		_ = Bind(c, &p1s)
		_ = Bind(c, &p2s)
		if xstring.JInt(p2s.Limit) > 0 {
			p1s.Limit = p2s.Limit
		}
		if xstring.JInt(p2s.Page) > 0 {
			p1s.Page = p2s.Page
		}
		p0 := xstring.JInt(p1s.Page)
		p1 := xstring.JInt(p1s.Limit)
		if p0 <= 0 {
			p0 = 1
		}
		if p1 <= 0 {
			p1 = 20
		}
		c.Set("_p0", p0)                   // 页码
		c.Set("p0", GetOffset(p0, p1))     // offset条数
		c.Set("page", p0)                  // 页码
		c.Set("limit", p1)                 // 查询条数
		c.Set("offset", GetOffset(p0, p1)) // 跳过条数
	}
	c.Next()
}

// 获取跳过条数
//
//	page	当前页
//	limit	每页条数
func GetOffset(page, limit int) int {
	if page <= 1 {
		page = 1
	}
	if limit <= 0 {
		limit = 0
	}
	return (page - 1) * limit
}
